package com.cv.framework.role.core.aop;

import cn.hutool.core.util.ObjUtil;
import com.cv.framework.common.exception.constants.GlobalErrorCodeConstants;
import com.cv.framework.role.core.annotations.RolePermit;
import com.cv.framework.security.core.utils.SecurityFrameworkUtil;
import com.cv.system.api.token.form.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;

import static com.cv.framework.common.exception.utils.ServiceExceptionUtil.exception;
import static com.cv.framework.common.exception.utils.ServiceExceptionUtil.exception0;

/**
 * 角色权限切面
 *
 * @author Charles_XDXD
 */
@Aspect
@Slf4j
public class RolePermitAspect {

    @Around("@annotation(com.cv.framework.role.core.annotations.RolePermit)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        RolePermit permits = signature.getMethod().getAnnotation(RolePermit.class);
        if (ObjUtil.isNotEmpty(permits)) {
            checkRole(permits.values());
        }
        return joinPoint.proceed();
    }

    /**
     * 检查角色
     *
     * @param role 角色
     */
    private void checkRole(String role) {
        LoginUser loginUser = SecurityFrameworkUtil.getLoginUser();

        if (ObjUtil.isEmpty(loginUser)) {
            throw exception0(GlobalErrorCodeConstants.UNAUTHORIZED.getCode(), "账号未登录或访问令牌已过期！");
        }

        assert loginUser != null;
        String roleName = loginUser.getRoleName();

        String[] roleList = role.split(":");

        if (roleList.length == 0) {
            return;
        }

        for (String code : roleList) {
            if (roleName.equals(code)) {
                return;
            }
        }

        throw exception(GlobalErrorCodeConstants.FORBIDDEN);
    }

}
